package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.config.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.mq.config.MqConst;
import com.atguigu.gmall.service.RabbitService;
import com.sun.org.apache.regexp.internal.RE;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/31  11:13
 * @description：TODO
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //查询秒杀列表
    @GetMapping("/list")
    public List<SeckillGoods>list(){
        return seckillGoodsService.list();
    }

    //秒杀详情页面
    @GetMapping("/{skuId}")
    public SeckillGoods getSeckillGoods(@PathVariable Long skuId){
        return seckillGoodsService.getSeckillGoods(skuId);
    }
    //立即抢购   目的：返回成功或失败   夹带  抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //校验是否开始抢购了 或是 库存 没有了
        //获取秒杀商品
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        //时间限制
        //结论： 参数1大于参数2为false     参数1小于等于参数2为true
        Date curTime = new Date();//当前时间
        Date startTime = seckillGoods.getStartTime();//开始时间
        Date endTime = seckillGoods.getEndTime();//结束时间

        if (DateUtil.dateCompare(endTime, curTime)) {
            // 2)当前时间  当前时间大于等于结束时间  商品活动已经结束
            return Result.fail().message("商品活动已经结束");
        }
        if (!DateUtil.dateCompare(startTime, curTime)) {
            //1)当前时间  开始时间大于当前时间 商品活动还没有开始
            return Result.fail().message("商品活动还没有开始");
        }
        //库存限制
        if (seckillGoods.getStockCount() <= 0) {
            //3)库存小于等于0 商品已经售完
            return Result.fail().message("商品已经售完");
        }
        //4）成功 返回 200 返回一个抢购码
        // UUID
        //时间戳
        //MD5  生成的抢购码
        String encrypt = MD5.encrypt(userId + "w:e" + skuId);
        return Result.ok(encrypt);
    }
    //秒杀微服务
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
        //秒杀微服务
        String userId = AuthContextHolder.getUserId(request);
        //1.校验抢购码
        String encrypt = MD5.encrypt(userId + "w:e" + skuId);
        if(!encrypt.equals(skuIdStr)){
            //如果不相同  使用Result.build可以放入枚举   传递不同的响应码  和返回值 比Result.fail更好一些
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //2.库存：状态位
       String status = (String) CacheHelper.get(skuId.toString());
        if("0".equals(status)){
            return Result.build(null,ResultCodeEnum.SECKILL_FINISH);//售完
        }
        //3.发消息
        UserRecode userRecode=new UserRecode();  //用户信息  加  商品信息
        userRecode.setSkuId(skuId);
        userRecode.setUserId(userId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,
                userRecode);
        //4.返回成功的信息
        return Result.ok();
    }
    //查询秒杀微服务   轮询3秒
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //秒杀微服务
        //1.是否有订单
        Object seckillOrder = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if(null !=seckillOrder){
            //下了单了
            return Result.build(null, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
        //2.是否有抢够资格
        Object seckillZiGe = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if(null !=seckillZiGe){
            //抢购成功 有资格了
            return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);
        }
        //3.用户是否购买过
        Object seckillUser = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId);
        if(null !=seckillUser){
            //抢购失败了
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }
        //4.校验状态位
        Object status = CacheHelper.get(skuId.toString());
        if("0".equals(status)){
            //卖完了
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        //5.排队中
        return Result.build(null, ResultCodeEnum.SECKILL_RUN);
    }

}
